﻿using System;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using System.Text;
using System.Diagnostics;

namespace DotNet.Common
{
	public class FormDragArg
	{
		private string m_fileExt;

		public event FileInvoker OnFileOpen;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="targetForm">MainForm</param>
		/// <param name="fileExt">.doc etc...</param>
		public void Load(Form targetForm,string fileExt,FileInvoker fileOpenFunc)
		{
			targetForm.AllowDrop = true;
			targetForm.DragDrop += FormMain_DragDrop;
			targetForm.DragEnter += FormMain_DragEnter;
			m_fileExt = fileExt;
			OnFileOpen += fileOpenFunc;

			OpenArgsFile();
		}

		private void OpenArgsFile()
		{
			string argFile = null;
			string[] cmds = Environment.GetCommandLineArgs();
			if (cmds.Length > 1)
			{
				if (string.IsNullOrEmpty(m_fileExt) || string.Compare(Path.GetExtension(cmds[1]), m_fileExt, true) == 0)
				{
					argFile = cmds[1];
				}
			}

			OpenFile(argFile);
		}

		public static void RegFileType(string fileExt,string fileDesc,string iconfilepath)
		{
			if(string.IsNullOrEmpty(fileExt) || fileExt.Length < 2 || fileExt[0] != '.')
				return;

			try
			{
				string fileType = fileExt.Substring(1, fileExt.Length - 1) + "File";
				RegistryKey key;

				key = Registry.ClassesRoot.CreateSubKey(fileExt, RegistryKeyPermissionCheck.ReadWriteSubTree);
				if (string.IsNullOrEmpty((string)key.GetValue(string.Empty)))
				{
					key.SetValue(string.Empty, fileType, RegistryValueKind.String);
				}

				key = Registry.ClassesRoot.CreateSubKey(fileType, RegistryKeyPermissionCheck.ReadWriteSubTree);
                if(!string.IsNullOrEmpty(fileDesc))
                {
                    if (string.IsNullOrEmpty((string)key.GetValue(string.Empty)))
                    {
                        key.SetValue(string.Empty, fileDesc, RegistryValueKind.String);
                    }
                }

                key = Registry.ClassesRoot.CreateSubKey(fileType + @"\DefaultIcon", RegistryKeyPermissionCheck.ReadWriteSubTree);
				if (string.IsNullOrEmpty((string)key.GetValue(string.Empty)))
				{
                    key.SetValue(string.Empty, iconfilepath, RegistryValueKind.ExpandString);
				}

                key = Registry.ClassesRoot.CreateSubKey(fileType + @"\shell\open\command", RegistryKeyPermissionCheck.ReadWriteSubTree);
				string command = string.Format("\"{0}\"  \"%1\"", Process.GetCurrentProcess().MainModule.FileName);
                key.SetValue(string.Empty, command, RegistryValueKind.ExpandString);

                Registry.ClassesRoot.Close();
			}
			catch //(Exception e)
			{
				// System.UnauthorizeAccessException(Not Administrator User)
			}
		}

		private void FormMain_DragEnter(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
			{
				string filepath = ((Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
				if (string.IsNullOrEmpty(m_fileExt) || string.Compare(Path.GetExtension(filepath), m_fileExt, true) == 0)
				{
					e.Effect = DragDropEffects.Link;
				}
			}
		}

		private void FormMain_DragDrop(object sender, DragEventArgs e)
		{
			if (e.Effect == DragDropEffects.Link)
			{
				string filepath = ((Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
				OpenFile(filepath);
			}
		}

		private bool OpenFile(string filepath)
		{
			try
			{
				if (OnFileOpen != null && !string.IsNullOrEmpty(filepath))
				{
					return OnFileOpen(filepath);
				}
				else
				{
					return true;
				}
			}
			catch
			{
				return false;
			}
		}
	}
}
